package com.pine.app.module.security.oauth.provider.token.converter;

import com.google.common.collect.Sets;
import com.pine.app.module.security.core.userdetails.UserDetails;
import com.pine.app.module.security.oauth.provider.DefaultOAuth2ClientRequest;
import com.pine.app.module.security.oauth.provider.token.OAuth2AccessToken;
import com.pine.app.module.security.oauth.provider.OAuth2Authentication;
import com.pine.app.module.security.oauth.provider.OAuth2ClientRequest;
import com.pine.app.module.security.oauth.user.service.UserDetailService;

import java.util.*;

/**
 * @author xiaoyuan
 * @create 2020/3/10 0:35
 **/
public class DefaultAccessTokenConverter implements AccessTokenConverter {

    private String clientIdAttribute = "client_id";
    private UserAuthenticationConverter userAuthenticationConverter;

    public DefaultAccessTokenConverter() {
        userAuthenticationConverter = new DefaultUserAuthenticationConverter();
    }

    public DefaultAccessTokenConverter(UserDetailService userDetailService) {
        this.userAuthenticationConverter = new DefaultUserAuthenticationConverter(userDetailService);
    }

    public DefaultAccessTokenConverter(UserAuthenticationConverter userAuthenticationConverter) {
        this.userAuthenticationConverter = userAuthenticationConverter;
    }


    @Override
    public Map<String, ?> convertAccessToken(OAuth2AccessToken var1, OAuth2Authentication var2) {
        return null;
    }

    @Override
    public OAuth2AccessToken extractAccessToken(String var1, Map<String, ?> var2) {
        return null;
    }

    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
        UserDetails user = this.userAuthenticationConverter.extractAuthentication(map);
        String clientId = (String) map.get(this.clientIdAttribute);
        Object scopes = map.get("scopes");
        Set<String> scope = new HashSet<>();
        if (scopes != null) {
            scope = Sets.newHashSet(scope.toString().split(","));
        }
        OAuth2ClientRequest request = new DefaultOAuth2ClientRequest(clientId, "",
                "", scope, map.get("resources") == null ? null :
                Sets.newHashSet(map.get("resources").toString().split(",")),
                null, (String) map.get("grant_type"), null, null);
        return new OAuth2Authentication(request, user);
    }
}
